package comm

// slice分片索引
type PartIndex struct {
	// inclusive, Low contains the low index of part
	Low int
	// exclusive, High contains the high index of part
	High int
}

// Partition 对一个长为size的slice分片
func Partition(size, chunkSize int) []PartIndex {
	if chunkSize <= 0 || size <= 0 {
		return nil
	}
	chunks := size/chunkSize + 1
	indices := make([]PartIndex, 0, chunks)
	for i := 0; i < size; i += chunkSize {
		indices = append(indices, PartIndex{Low: i, High: i + chunkSize})
	}
	return indices
}

// DoWithPartition 对一个长为size的slice分片分片处理
func DoWithPartition(size, chunkSize int, handle func(low, high int) error) (finished int, err error) {
	if chunkSize <= 0 || size <= 0 {
		return
	}
	for finished = 0; finished < size; finished += chunkSize {
		err = handle(finished, MinInt(finished+chunkSize, size))
		if err != nil {
			return
		}
	}
	return MinInt(finished, size), nil
}
